import os
import sys
from PyQt5.QtWidgets import QWidget, QMenu, QAction, QApplication, QMessageBox, QSystemTrayIcon
from PyQt5.QtGui import QPainter, QPixmap, QColor, QFont
from PyQt5.QtCore import Qt, QPoint, QTimer
from .SystemTray import SystemTray
from .FishingPlugin import FishingPlugin


class FloatingBall(QWidget):
    def __init__(self, path):
        super().__init__()
        self.path = path
        self.base_image_path = os.path.join(path, "resource/miniq.png")
        self.loading_image_path = os.path.join(path, "resource/loading.png")
        self.current_image_path = self.loading_image_path

        self.loading_complete = False  # 加载状态标记

        # 拖拽相关变量
        self.dragging = False
        self.oldPos = None

        # 插件相关配置
        self.plugin_classes = {
            "fishing": {
                "class": FishingPlugin,
                "name": "钓鱼",
                "description": "开启钓鱼模式"
            }
            # 其他插件配置...
        }
        self.active_plugins = {}  # 存储当前激活的插件实例

        # 初始化系统托盘
        self.tray = SystemTray(self)
        self.menu = QMenu(self)

        # 初始化UI和菜单
        self.init_ui()
        self.init_menu()

        self.start_loading()
        # QTimer.singleShot(100, self._preload_and_show)  # 延迟100ms避免影响启动速度

    def start_loading(self):
        self.show()
        self._preload_menu()
        self.complete_loading()
        # ... 加载逻辑 ...

    def complete_loading(self):
        """完成加载，切换到主图片"""
        # 标记加载完成
        self.loading_complete = True
        # 切换到基础图片
        self.current_image_path = self.base_image_path
        # 刷新界面显示新图片
        self.hide()
        self.move_to_initial_position()
        self.update()
        self.show()

    def _preload_and_show(self):
        """执行预加载并在完成后显示窗口"""
        self._preload_menu()
        # 预加载完成后显示悬浮窗
        self.show()
        # 确保窗口在正确位置
        self.move_to_initial_position()

    def _preload_menu(self):
        """预加载菜单，在后台完成首次渲染和尺寸计算"""
        if hasattr(self, 'menu'):
            # 在屏幕外显示菜单以触发渲染，然后立即隐藏
            self.menu.popup(QPoint(-1000, -1000))
            self.menu.hide()
            print("菜单预加载完成")

    def init_ui(self):
        self.base_size = (100, 100)
        self.setWindowFlags(
            Qt.FramelessWindowHint |
            Qt.WindowStaysOnTopHint |
            Qt.Tool
        )
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setAttribute(Qt.WA_ShowWithoutActivating, False)
        self.setFixedSize(*self.base_size)

    def move_to_initial_position(self):
        screen_geometry = QApplication.desktop().availableGeometry()
        screen_width = screen_geometry.width()
        self.move(screen_width - self.width() - 500, 500)

    def create_plugin_instance(self, plugin_name):
        """创建插件实例并绑定信号"""
        if plugin_name in self.plugin_classes:
            plugin_class = self.plugin_classes[plugin_name]["class"]
            plugin_instance = plugin_class(self)

            # 绑定插件关闭信号，用于恢复悬浮球显示
            plugin_instance.window_closed.connect(self.on_plugin_window_closed)

            self.active_plugins[plugin_name] = plugin_instance
            print(f"创建插件实例: {plugin_name}")
            return plugin_instance
        else:
            raise ValueError(f"未知插件: {plugin_name}")

    def destroy_plugin_instance(self, plugin_name):
        """销毁插件实例"""
        if plugin_name in self.active_plugins:
            # 断开信号连接
            self.active_plugins[plugin_name].window_closed.disconnect(
                self.on_plugin_window_closed)
            del self.active_plugins[plugin_name]
            print(f"销毁插件实例: {plugin_name}")

    def on_plugin_window_closed(self, plugin_name):
        """插件窗口关闭时的回调"""
        self.show()  # 恢复显示悬浮球
        self.destroy_plugin_instance(plugin_name)

    def init_menu(self):

        # 自动添加所有插件的菜单项
        for plugin_name, plugin_info in self.plugin_classes.items():
            action = QAction(
                plugin_info["name"],
                self,
                triggered=lambda checked, name=plugin_name: self.toggle_plugin(
                    name)
            )
            if "description" in plugin_info:
                action.setStatusTip(plugin_info["description"])
            self.menu.addAction(action)

        self.menu.addSeparator()

        self.hideAction = QAction("隐藏", self, triggered=self.hide)
        self.menu.addAction(self.hideAction)

        self.exitAction = QAction("退出", self, triggered=self.close)
        self.menu.addAction(self.exitAction)

    def contextMenuEvent(self, event):
        """简化的右键菜单处理：直接在点击位置显示"""
        self.activateWindow()
        # 直接使用鼠标点击的全局位置显示菜单
        self.menu.exec_(event.globalPos())

    def toggle_plugin(self, plugin_name):
        """切换插件状态：激活时隐藏悬浮球显示插件窗口，关闭时反之"""
        try:
            if plugin_name in self.active_plugins:
                # 关闭插件
                self.active_plugins[plugin_name].close_window()
            else:
                # 激活插件：隐藏悬浮球，显示插件窗口
                self.hide()
                plugin = self.create_plugin_instance(plugin_name)
                plugin.show_window()
        except Exception as e:
            QMessageBox.warning(
                self,
                "插件错误",
                f"操作{self.plugin_classes[plugin_name]['name']}时出错: {str(e)}"
            )
            self.show()  # 出错时确保悬浮球能显示

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        pixmap = QPixmap(self.current_image_path)
        if not pixmap.isNull():
            scaled_pixmap = pixmap.scaled(
                event.rect().size(),
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )
            x = (event.rect().width() - scaled_pixmap.width()) // 2
            y = (event.rect().height() - scaled_pixmap.height()) // 2
            painter.drawPixmap(x, y, scaled_pixmap)
        else:
            painter.fillRect(event.rect(), QColor(200, 200, 200, 150))
            painter.setPen(QColor(255, 0, 0))
            font = QFont()
            font.setFamily("SimHei")
            painter.setFont(font)
            painter.drawText(event.rect(), Qt.AlignCenter, "图片缺失")
            print(f"无法加载图片: {self.current_image_path}")

    # 鼠标事件处理
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.oldPos = event.globalPos()
        # super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.dragging and self.oldPos:
            delta = event.globalPos() - self.oldPos
            self.move(self.x() + delta.x(), self.y() + delta.y())
            self.oldPos = event.globalPos()
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = False
        super().mouseReleaseEvent(event)

    def closeEvent(self, event):
        # 关闭所有活跃插件
        for plugin_name in list(self.active_plugins.keys()):
            self.active_plugins[plugin_name].close_window()
            self.destroy_plugin_instance(plugin_name)
        event.accept()
